package com.example.workapp;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.Nullable;
import okhttp3.*;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

public class CollaborativeEditor extends AppCompatActivity {
    private static final int FILE_SELECT_CODE = 1;
    private static final String UPLOAD_URL = "http://101.200.164.160:5000/postfile"; // 替换成你的上传地址

    private void selectFile() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{
                "application/msword",  // .doc
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .docx
                "application/vnd.ms-excel",  // .xls
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" // .xlsx
        });
        startActivityForResult(intent, FILE_SELECT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                Uri selectedFileUri = data.getData();
                uploadFile(selectedFileUri);
            }
        }
    }

    // 上传文件
    private void uploadFile(Uri fileUri) {
        File file = getFileFromUri(fileUri);
        if (file == null) {
            Log.e("Upload", "File conversion failed");
            return;
        }

        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", getFileName(fileUri), RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .build();

        Request request = new Request.Builder()
                .url(UPLOAD_URL)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.e("Upload", "Upload failed: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.d("Upload", "Upload successful: " + response.body().string());

                    // 请求成功后的操作，跳转到webview页面
                    runOnUiThread(() -> {
                        Intent intent = new Intent(CollaborativeEditor.this, WebActivity.class);
                        intent.putExtra("filename",getFileName(fileUri));
                        EditText usernameInput=findViewById(R.id.editUsername);
                        intent.putExtra("username",usernameInput.getText().toString());
                        startActivity(intent);
                    });
                } else {
                    Log.e("Upload", "Upload failed: " + response.message());
                }
            }
        });
    }
    // 将 URI 转换为本地文件（适用于 Android 10+）
    private File getFileFromUri(Uri uri) {
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            File tempFile = File.createTempFile("upload", ".tmp", getCacheDir());
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.close();
            inputStream.close();
            return tempFile;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 获取文件名
    private String getFileName(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor == null) return "unknown";
        int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        cursor.moveToFirst();
        String fileName = cursor.getString(nameIndex);
        cursor.close();
        return fileName;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_collaborative_editor);
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//            return insets;
//        });
        Button to_webview_btn=findViewById(R.id.webview_btn);
        to_webview_btn.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              //打开webview active
              Intent intent = new Intent(CollaborativeEditor.this, WiFiActivity.class);
              intent.putExtra("flag",1);
              intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
              startActivity(intent);
              // finish();
          }
      });
        Button wait_to_edit_btn=findViewById(R.id.wait_edit_btn);
        wait_to_edit_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CollaborativeEditor.this, WifiClientActivity.class);
                intent.putExtra("flag",1);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }
}